// 仪表盘指标API服务 - 访客数据、留言订阅数据、博客数据
const express = require('express');
const router = express.Router();
const { authenticateToken } = require('../middleware/auth');
const { getMongoDB } = require('../config/multi-database');

// 获取仪表盘指标数据
router.get('/dashboard/metrics', authenticateToken, async (req, res) => {
    try {
        const db = await getMongoDB();
        
        // 获取今日访客数据
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        const tomorrow = new Date(today);
        tomorrow.setDate(tomorrow.getDate() + 1);
        
        // 访客数据统计
        const visitorsToday = await db.collection('visitor_logs').countDocuments({
            timestamp: { $gte: today, $lt: tomorrow }
        });
        
        // 昨日访客数据（用于计算变化率）
        const yesterday = new Date(today);
        yesterday.setDate(yesterday.getDate() - 1);
        const dayBeforeYesterday = new Date(yesterday);
        dayBeforeYesterday.setDate(dayBeforeYesterday.getDate() - 1);
        
        const visitorsYesterday = await db.collection('visitor_logs').countDocuments({
            timestamp: { $gte: yesterday, $lt: today }
        });
        
        const visitorsChange = visitorsYesterday > 0 ? 
            ((visitorsToday - visitorsYesterday) / visitorsYesterday * 100).toFixed(1) : 0;
        
        // 页面浏览量统计
        const pageViewsToday = await db.collection('page_views').countDocuments({
            timestamp: { $gte: today, $lt: tomorrow }
        });
        
        const pageViewsYesterday = await db.collection('page_views').countDocuments({
            timestamp: { $gte: yesterday, $lt: today }
        });
        
        const pageViewsChange = pageViewsYesterday > 0 ? 
            ((pageViewsToday - pageViewsYesterday) / pageViewsYesterday * 100).toFixed(1) : 0;
        
        // 新留言统计
        const newMessages = await db.collection('messages').countDocuments({
            status: 'pending',
            createdAt: { $gte: today, $lt: tomorrow }
        });
        
        const newMessagesYesterday = await db.collection('messages').countDocuments({
            status: 'pending',
            createdAt: { $gte: yesterday, $lt: today }
        });
        
        const messagesChange = newMessagesYesterday > 0 ? 
            ((newMessages - newMessagesYesterday) / newMessagesYesterday * 100).toFixed(1) : 0;
        
        // 邮件订阅统计
        const totalSubscribers = await db.collection('email_subscribers').countDocuments({
            status: 'active'
        });
        
        const newSubscribersToday = await db.collection('email_subscribers').countDocuments({
            createdAt: { $gte: today, $lt: tomorrow }
        });
        
        const subscribersChange = totalSubscribers > 0 ? 
            (newSubscribersToday / totalSubscribers * 100).toFixed(1) : 0;
        
        // 博客数据统计
        const totalArticles = await db.collection('blog_articles').countDocuments({
            status: 'published'
        });
        
        const newArticlesThisMonth = await db.collection('blog_articles').countDocuments({
            status: 'published',
            publishedAt: { 
                $gte: new Date(today.getFullYear(), today.getMonth(), 1),
                $lt: new Date(today.getFullYear(), today.getMonth() + 1, 1)
            }
        });
        
        const articlesChange = totalArticles > 0 ? 
            (newArticlesThisMonth / totalArticles * 100).toFixed(1) : 0;
        
        // 博客阅读量统计
        const blogReadsToday = await db.collection('blog_reads').countDocuments({
            timestamp: { $gte: today, $lt: tomorrow }
        });
        
        const blogReadsYesterday = await db.collection('blog_reads').countDocuments({
            timestamp: { $gte: yesterday, $lt: today }
        });
        
        const readsChange = blogReadsYesterday > 0 ? 
            ((blogReadsToday - blogReadsYesterday) / blogReadsYesterday * 100).toFixed(1) : 0;
        
        // 返回整合的指标数据
        const metricsData = {
            // 访客数据
            todayVisitors: visitorsToday,
            visitorsChange: parseFloat(visitorsChange),
            pageViews: pageViewsToday,
            pageViewsChange: parseFloat(pageViewsChange),
            
            // 留言订阅数据
            newMessages: newMessages,
            messagesChange: parseFloat(messagesChange),
            emailSubscribers: totalSubscribers,
            subscribersChange: parseFloat(subscribersChange),
            
            // 博客数据
            blogArticles: totalArticles,
            articlesChange: parseFloat(articlesChange),
            blogReads: blogReadsToday,
            readsChange: parseFloat(readsChange),
            
            // 时间戳
            lastUpdated: new Date()
        };
        
        res.json({
            success: true,
            data: metricsData
        });
        
    } catch (error) {
        console.error('获取仪表盘指标数据失败:', error);
        res.status(500).json({
            success: false,
            message: '获取仪表盘指标数据失败'
        });
    }
});

// 获取访客趋势数据
router.get('/dashboard/visitor-trends', authenticateToken, async (req, res) => {
    try {
        const db = await getMongoDB();
        const { period = '7d' } = req.query; // 7d, 30d, 90d
        
        let days = 7;
        if (period === '30d') days = 30;
        if (period === '90d') days = 90;
        
        const startDate = new Date();
        startDate.setDate(startDate.getDate() - days);
        
        // 按天统计访客数据
        const visitorTrends = await db.collection('visitor_logs').aggregate([
            {
                $match: {
                    timestamp: { $gte: startDate }
                }
            },
            {
                $group: {
                    _id: {
                        $dateToString: {
                            format: '%Y-%m-%d',
                            date: '$timestamp'
                        }
                    },
                    count: { $sum: 1 }
                }
            },
            {
                $sort: { _id: 1 }
            }
        ]).toArray();
        
        res.json({
            success: true,
            data: visitorTrends
        });
        
    } catch (error) {
        console.error('获取访客趋势数据失败:', error);
        res.status(500).json({
            success: false,
            message: '获取访客趋势数据失败'
        });
    }
});

// 获取博客阅读趋势
router.get('/dashboard/blog-trends', authenticateToken, async (req, res) => {
    try {
        const db = await getMongoDB();
        const { period = '7d' } = req.query;
        
        let days = 7;
        if (period === '30d') days = 30;
        if (period === '90d') days = 90;
        
        const startDate = new Date();
        startDate.setDate(startDate.getDate() - days);
        
        // 按天统计博客阅读量
        const blogTrends = await db.collection('blog_reads').aggregate([
            {
                $match: {
                    timestamp: { $gte: startDate }
                }
            },
            {
                $group: {
                    _id: {
                        $dateToString: {
                            format: '%Y-%m-%d',
                            date: '$timestamp'
                        }
                    },
                    count: { $sum: 1 }
                }
            },
            {
                $sort: { _id: 1 }
            }
        ]).toArray();
        
        res.json({
            success: true,
            data: blogTrends
        });
        
    } catch (error) {
        console.error('获取博客阅读趋势失败:', error);
        res.status(500).json({
            success: false,
            message: '获取博客阅读趋势失败'
        });
    }
});

// 获取留言统计
router.get('/dashboard/message-stats', authenticateToken, async (req, res) => {
    try {
        const db = await getMongoDB();
        
        // 留言状态统计
        const messageStats = await db.collection('messages').aggregate([
            {
                $group: {
                    _id: '$status',
                    count: { $sum: 1 }
                }
            }
        ]).toArray();
        
        // 最近7天留言趋势
        const sevenDaysAgo = new Date();
        sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
        
        const messageTrends = await db.collection('messages').aggregate([
            {
                $match: {
                    createdAt: { $gte: sevenDaysAgo }
                }
            },
            {
                $group: {
                    _id: {
                        $dateToString: {
                            format: '%Y-%m-%d',
                            date: '$createdAt'
                        }
                    },
                    count: { $sum: 1 }
                }
            },
            {
                $sort: { _id: 1 }
            }
        ]).toArray();
        
        res.json({
            success: true,
            data: {
                stats: messageStats,
                trends: messageTrends
            }
        });
        
    } catch (error) {
        console.error('获取留言统计失败:', error);
        res.status(500).json({
            success: false,
            message: '获取留言统计失败'
        });
    }
});

module.exports = router;